1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| static int heapLen; public static int[] heapSort(int[] arr) { heapLen = arr.length; buildMaxHeap(arr); for (int i = arr.length - 1; i > 0; i--) { swap(arr, 0, i); heapLen --; heapify(arr, 0); } return arr; } public static void swap(int[] arr, int i, int j) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } public static void buildMaxHeap(int[] arr) { for (int i = arr.length / 2 - 1; i >= 0; i--) { heapify(arr, i); } } public static void heapify(int[] arr, int i) { int left = 2 * i + 1; int right = 2 * i + 2; int largest = i; if (right < heapLen && arr[right] > arr[largest]) largest = right; if (left < heapLen && arr[left] > arr[largest]) largest = left; if (largest != i) { swap(arr, largest, i); heapify(arr, largest); } }
|